<template>
  <scroll-dialog ref="dialogRef" title="修改价格" width="1000px" :dialogVisible="isVisible" @clickSubmit="clickSubmit"
                 @close="close">
    <el-form ref="formRef" :model="formModel" label-width="100px">
      <xm-f-radio quick prop="status" v-model="formModel.status" label="改价维度:" :options="modifyTypes"
                  @change="() => modifyPriceChange()"></xm-f-radio>

      <template v-if="formModel.status === '整单改价'">
        <XmFIntput quick v-model="formModel.oncePrice.modifyPrice" prop="oncePrice.modifyPrice" v-number:2 label="修改价格:"
                   @input="modifyPriceChange"></XmFIntput>

        <XmFIntput quick v-number:2 @input="modifyPriceChange" v-model="formModel.oncePrice.modifyFreight"
                   prop="oncePrice.modifyFreight" label="修改运费:"></XmFIntput>
      </template>

      <template v-else>
        <el-table ref="tableRef" :data="tableData">
          <el-table-column label="商品信息">
            <template #default="scope">
              <div class="cell-img">
                <ImageView v-model="scope.row.images"></ImageView>
                <div>
                  <el-popover placement="top-start" :width="200" trigger="hover" title="商品名"
                              :content="scope.row.goodsTitle">
                    <template #reference>
                      <span>{{ scope.row.goodsTitle }}</span>
                    </template>
                  </el-popover>
                  <span>{{ scope.row.specValue }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="tmpGoodsPrice" label="原价(元)"></el-table-column>
          <el-table-column prop="num" label="数量" width="80"></el-table-column>
          <el-table-column prop="total" label="商品应付金额"></el-table-column>
          <el-table-column label="修改单价">
            <template #default="scoped">
              <el-select v-model="scoped.row.operator" class="m-2" placeholder="Select" size="large" @change="
                  () => {
                    scoped.row.modifyPrice = ''
                    modifyPriceChange()
                  }
                ">
                <el-option v-for="item in modifyValueTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-input v-if="scoped.row.operator === '打折'" v-model="scoped.row.modifyPrice"
                        @input="positiveInteger(scoped.row)" @change="modifyPriceChange">
                <template #append>%</template>
              </el-input>
              <el-input v-else v-model="scoped.row.modifyPrice" v-number:2 @change="modifyPriceChange"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="改后金额" prop="afterPrice">
            <template #default="{ row }">
              {{ filterTitle(row) }}
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-form-item label="改后订单总价">
        <span>{{ total }}</span>
      </el-form-item>
    </el-form>
  </scroll-dialog>
</template>
<script lang="ts" setup>
  import { ref, watch, computed, watchEffect } from 'vue'
  import ScrollDialog from '@/components/ScrollDialog/index.vue'
  import { modifyPrice, modifyGoodsPrice } from '@/api/modules/shop'
  import { usePromise } from '@/hooks/core/usePromise'
  import common from '@/utils/common'
  import ImageView from '@/components/ImageView/index.vue'
  import { cloneDeep } from 'lodash'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated'

  const props = defineProps({
    modifyPriceDialog: {
      type: Boolean,
      default() {
        return false
      },
    },
    id: {
      type: Number,
    },
    orderData: {
      type: Object,
      default() {
        return {}
      },
    },
  })
  const isVisible = ref(false)
  watch(
    () => props.modifyPriceDialog,
    (val) => {
      isVisible.value = props.modifyPriceDialog
      if (isVisible.value) {
        const { orderDetails, freightAmount, orderAmount, variableAmount } =
          props.orderData
        if (!orderDetails) return
        const tmpOrder = cloneDeep(orderDetails)
        formModel.value.oncePrice.modifyPrice =
          (orderAmount + variableAmount) / 100
        formModel.value.oncePrice.modifyFreight = freightAmount / 100
        modifyPriceChange()
        initTableData()
      }
    },
    { immediate: true }
  )

  // watch(
  //   () => props.orderData,
  //   (val) => {
  //
  //   },
  //   { immediate: true }
  // )
  // onMountedOrActivated(() => {
  //   const { orderDetails, freightAmount, orderAmount } = props.orderData
  //   if (!orderDetails) return
  //   const tmpOrder = cloneDeep(orderDetails)
  //   formModel.value.oncePrice.modifyPrice = orderAmount / 100
  //   formModel.value.oncePrice.modifyFreight = freightAmount / 100
  //   modifyPriceChange()
  // })
  const formModel = ref({
    status: '整单改价',
    oncePrice: {
      modifyFreight: 0,
      modifyPrice: 0,
    },
  })

  const modifyTypes = ref([
    { label: '整单改价', value: 0 },
    { label: '商品改价', value: 1 },
  ])

  const modifyValueTypes = ref([
    { label: '一口价', value: '一口价' },
    { label: '降价', value: '降价' },
    { label: '涨价', value: '涨价' },
    { label: '打折', value: '打折' },
  ])
  const emit = defineEmits(['update:modifyPriceDialog', 'addSuccess'])

  const formRef = ref()
  function clickSubmit() {
    formRef.value.validate((valid: Boolean) => {
      if (valid) {
        console.log('formModel.value =' + JSON.stringify(formModel.value))
        if (formModel.value.status === '商品改价') {
          updateMultipleValue()
        } else {
          updateOncePrice()
        }
      }
    })
  }
  function close() {
    formModel.value = {
      status: '整单改价',
      oncePrice: {
        modifyFreight: 0,
        modifyPrice: 0,
      },
    }
    emit('update:modifyPriceDialog', false)
  }

  const { to } = usePromise()
  const tableData = ref()
  function initTableData() {
    const { orderDetails } = props.orderData
    if (!orderDetails) return []
    const tmpOrder = cloneDeep(orderDetails)
    tableData.value = tmpOrder.map((item: any) => {
      item.operator = '一口价'
      item.modifyPrice = ''
      item.total = (item.goodsPrice * item.num) / 100 + '元'
      item.images = [{ url: item.goodsImage }]
      item.skuId = item.goodsSkuId
      item.tmpGoodsPrice = item.goodsPrice / 100
      if (item.goodsSpecValues) {
        item.specValue = '规格: ' + item.goodsSpecValues.join('&')
      } else {
        item.specValue = '单规格'
      }
      return item
    })
  }

  const filterTitle = computed(() => (item: any) => {
    const checkPrice = checkOperator(item)
    return checkPrice * item.num + '元'
  })

  function checkOperator(item: any) {
    const { goodsPrice, operator } = item
    const modifyPrice = parseFloat(item.modifyPrice)
    let checkPrice = 0

    switch (operator) {
      case '一口价':
        checkPrice = modifyPrice
        break
      case '降价':
        checkPrice = (goodsPrice - modifyPrice * 100) / 100
        break
      case '涨价':
        checkPrice = (goodsPrice + modifyPrice * 100) / 100
        break
      case '打折':
        checkPrice = (goodsPrice * modifyPrice) / 10000
        break
    }
    return !modifyPrice ? goodsPrice / 100 : checkPrice
  }

  const total = ref()
  function modifyPriceChange() {
    if (
      formModel.value.status === '商品改价' &&
      Array.isArray(tableData.value)
    ) {
      let all = 0
      tableData.value.forEach((item: any) => {
        all = all + checkOperator(item) * item.num
      })

      total.value = all + '元'
    } else {
      const { modifyPrice, modifyFreight } = formModel.value.oncePrice
      if (modifyPrice) {
        total.value = parseFloat(modifyPrice as any)
      }
      if (modifyFreight) {
        total.value += parseFloat(modifyFreight as any)
      }
      total.value += '元'
    }
  }
  function positiveInteger(item: any) {
    const reg1 = /^\d{0,2}$/
    const b = reg1.test(item.modifyPrice)
    
    if (!b) {
      item.modifyPrice = ''
      common.XmMessage(1, '请输入两位整数, 例如75即为75折')
      // modifyPriceChange()
    }
  }
  // 显示选中的物品
  // 一口
  async function updateOncePrice() {
    const { modifyPrice: tmpModifyPrice, modifyFreight } =
      formModel.value.oncePrice
    common.XmLoading(true)
    const [err, res] = await to(
      modifyPrice({
        id: props.id as number,
        modifyPrice: parseFloat(tmpModifyPrice as any) * 100,
        modifyFreight: parseFloat(modifyFreight as any) * 100,
      })
    )
    common.XmLoading()
    if (!err) {
      common.XmMessage(0, '修改成功')
      emit('addSuccess', res.data)
      emit('update:modifyPriceDialog', false)
    }
  }

  async function updateMultipleValue() {
    const skuPriceList = tableData.value.map((item: any) => {
      const { skuId, modifyPrice: tmpModifyPrice, operator } = item
      const modifyPrice =
        parseFloat(tmpModifyPrice) * (operator === '打折' ? 1 : 100)
      return { skuId, modifyPrice, operator }
    })
    common.XmLoading(true)
    const [err, res] = await to(
      modifyGoodsPrice({ id: props.id, skuPriceList })
    )
    common.XmLoading()
    if (!err) {
      common.XmMessage(0, '修改成功')
      emit('addSuccess', res.data)
      emit('update:modifyPriceDialog', false)
    }
  }
</script>
<style lang="scss" scoped>
.cell-img {
  display: flex;

  .imageView-container {
    width: 80px;
    height: 80px;
    border-radius: 5px;
  }

  span {
    margin-left: 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }
}
</style>
